use loco_rs::prelude::*;
use sea_orm::DeleteResult;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::cart_items::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub customer_id: String,
    pub product_id: String,
    pub sku_code: String,
    pub guest_id: String,
    pub selected: i8,
    pub quantity: u32,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Customer ID must not be empty."))]
    pub customer_id: String,
    #[validate(length(min = 1, message = "Product ID must not be empty."))]
    pub product_id: String,
    #[validate(length(min = 1, message = "SKU code must not be empty."))]
    pub sku_code: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            customer_id: self.customer_id.as_ref().to_owned(),
            product_id: self.product_id.as_ref().to_owned(),
            sku_code: self.sku_code.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::cart_items::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a cart item by the provided id
    ///
    /// # Errors
    ///
    /// When could not find cart item or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let cart_item = cart_items::Entity::find()
            .filter(
                model::query::condition()
                    .eq(cart_items::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        cart_item.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds cart items by the provided customer id
    ///
    /// # Errors
    ///
    /// When could not find cart items or DB query error
    pub async fn find_by_customer_id(
        db: &DatabaseConnection,
        customer_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let cart_items = cart_items::Entity::find()
            .filter(
                model::query::condition()
                    .eq(cart_items::Column::CustomerId, customer_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(cart_items)
    }

    /// finds cart items by the provided guest id
    ///
    /// # Errors
    ///
    /// When could not find cart items or DB query error
    pub async fn find_by_guest_id(
        db: &DatabaseConnection,
        guest_id: &str,
    ) -> ModelResult<Vec<Self>> {
        let cart_items = cart_items::Entity::find()
            .filter(
                model::query::condition()
                    .eq(cart_items::Column::GuestId, guest_id)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(cart_items)
    }

    /// Asynchronously creates a cart item and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the cart item into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let cart_item = cart_items::ActiveModel {
            customer_id: ActiveValue::set(params.customer_id.to_string()),
            product_id: ActiveValue::set(params.product_id.to_string()),
            sku_code: ActiveValue::set(params.sku_code.to_string()),
            guest_id: ActiveValue::set(params.guest_id.to_string()),
            selected: ActiveValue::set(params.selected),
            quantity: ActiveValue::set(params.quantity),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(cart_item)
    }

    /// Soft deletes the cart item
    ///
    /// # Errors
    ///
    /// When could not delete the cart item from the DB
    pub async fn delete(self, db: &DatabaseConnection) -> ModelResult<DeleteResult> {
        let model: cart_items::ActiveModel = self.into();
        Ok(model.delete(db).await?)
    }
}

impl ActiveModel {
    /// Updates the cart item's quantity
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_quantity(
        mut self,
        db: &DatabaseConnection,
        quantity: u32,
    ) -> ModelResult<Model> {
        self.quantity = ActiveValue::set(quantity);
        Ok(self.update(db).await?)
    }

    /// Updates the cart item's selected status
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_selected_status(
        mut self,
        db: &DatabaseConnection,
        selected: bool,
    ) -> ModelResult<Model> {
        self.selected = ActiveValue::set(if selected { 1 } else { 0 });
        Ok(self.update(db).await?)
    }
}
